import Canvas from './Canvas.js';
import Snake from './Snake.js';
import { snakes } from './Snake.js';
import Bug from './Bug.js';
import Play from './Play.js';

export default class App {
    constructor(options) {
        this.options = Object.assign(
            {
                width: 600,
                height: 400,
            },
            options
        );

        this.canvas = new Canvas(this);
        this.validate();
        //创建蛇
        this.snake({ bgColor: 'green', ...this.randomPosition() });
        //创建虫子
        this.bug();
        //创建动画
        this.play=new Play(this);
        //创建游戏记录
        this.total = this.createTotal();
        //创建开始按钮
        this.begin=this.createBegin()
        
    }

    createBegin() {
        let button=document.createElement('button')
        button.innerHTML=`开始`
        button.style.fontWeight = 'bold'
        button.onclick=this.play.restart.bind(this.play)
        document.body.insertAdjacentElement('beforeEnd',button)

        return button
    }

    createTotal() {
        let div = document.createElement('div');
        div.innerHTML = '努力吃更多的虫子吧';
        div.style.fontWeight = 'bold';
        document.body.insertAdjacentElement('afterbegin', div);
        return div;
    }

    renderTotal(content='') {
        this.total.textContent=`${content}你一共吃了${Snake.count}只`
    }

    validate() {
        if (this.options.width % 50 || this.options.height % 50)
            throw new Error('画布宽高与格子大小必须整除');
    }

    snake(options) {
        let snake = new Snake(this, options);
        this.canvas.el.insertAdjacentElement('beforeEnd', snake.el);
    }

    bug() {
        let position;
        while ((position = this.randomPosition())) {
            let state = snakes.some((snake) => {
                return snake.left == position.left && snake.top == position.top;
            });

            if (!state) break;
        }
        let bug = new Bug(this, position);
        this.canvas.el.insertAdjacentElement('beforeEnd', bug.el);
    }

    randomPosition() {
        let left = Math.floor((Math.random() * this.options.width) / 50) * 50;
        let top = Math.floor((Math.random() * this.options.height) / 50) * 50;
        return { left, top };
    }
}
